package cn.wmx.config;

import cn.wmx.pojo.Configuration;
import cn.wmx.pojo.MappedStatement;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 用于解析 Mapper.xml 文件，
 * 将解析的Mapper.xml文件的每个标签封装到MappedStatement中
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration = configuration;
    }

    /**
     * 解析文件，将 mapper.xml 中标签封装 MappedStatement 对象
     * 根据 statementId put 到 Configuration 对象的 Map 中
     *
     * @param inputStream
     * @throws DocumentException
     */
    public void parseMapper(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        // 获取 mapper.xml 中 <mapper> 的属性 namespace 的值，此时还不是完整的 statementId
        String statementId = rootElement.attributeValue("namespace");
        List<Element> list = getElementList(rootElement);
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("parameterType");
            String sql = element.getTextTrim();
            String tagName = element.getName();
            MappedStatement mappedStatement = new MappedStatement();
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sql);
            mappedStatement.setTagName(tagName);
            configuration.getMappedStatementMap().put(statementId + "." + id, mappedStatement);
        }
    }

    public List<Element> getElementList(Element rootElement) {
        List<Element> list = new ArrayList<>();
        String[] tags = {"//select", "//update", "//insert", "//delete"};
        for (String tag : tags) {
            List<Element> elements = rootElement.selectNodes(tag);
            if (elements != null && elements.size() > 0) list.addAll(elements);
        }
        return list.size() > 0 ? list : Collections.emptyList();
    }

}
